import { unioformDateTransform} from '../../utils/index.js';

import  tableModule from '../../models/index.js';
import fs from 'fs'
import  path from 'path';

import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);


const {
    usersModel,
    userLoginStatusModel
} = tableModule

// 添加日志记录
function logRecord(req,res,next){
  let {url,ip} = req
  let date = new Date()
  let dateDay = date.toLocaleString('zh-CN').split(' ')[0].replaceAll('/','-')
  let time = date.toLocaleTimeString('zh-CN')
  let path1 = `${dateDay}-access.log`
  fs.appendFileSync(path.resolve(__dirname,`../../logs/${path1}`), `${url}   ${ip}    ${time} \r\n`)
  next()
}



//检查用户是否登录
async function  checkLogin(req, res, next) {
    const token = req.get("Token")
    if (!token) {
        return res.status(403).json({ 
            code:403,
            message:"用户未登录",
            data:null
        });
    }

    //判断token是否过期
    let user = await userLoginStatusModel.getUserLoginStatus(token)
    if (!user) {
        return res.status(403).json({ 
            code:403,
            message:"token已过期",
            data:null
        });
    }

    //每次调用接口都要更新token过期时间
    let expiredTime = unioformDateTransform(new Date().getTime() + 20*60*1000)
    let updateRes = await userLoginStatusModel.updateUserLoginStatus(token, {expiredTime})
    if(updateRes){
        req.userId = user.userId; // 将用户id信息存储在请求对象中传递给下一个中间件
        next();
    }else{
        return res.status(500).json({
            code:500,
            message:"更新用户登录状态失败",
            data:null
        });
    }
}


//判断用户以及所属的角色信息是否存在
async function checkUserRole(req,res,next){
    const {userId} = req
    const {roleCode} = req.body

    if(!userId || !roleCode){
         return res.status(500).json({
            code:500,
            message:"用户角色信息不完整",
            data:null
        })
    }

    let user = await usersModel.getUserByUniqueIdentifier({userId})

    if(!(typeof user.roles == 'string' ? JSON.parse(user.roles) : user.roles)?.includes(roleCode)){

        return res.status(500).json({
            code:500,
            message:"当前用户或角色信息不存在"
        })
    }
    req.user = user
    next()
}



export {checkLogin,checkUserRole, logRecord}